<template>
  <div class="upload-photos">
    <el-upload
      class="upload-demo"
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-change="handleChange"
      :on-progress="handleProgress"
      :before-upload="beforeUpload"
      :limit="3"
      :on-exceed="handleExceed"
      list-type="picture-card"
      multiple
    >
      <el-button type="primary">点击上传</el-button>
      <template #tip>
        <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </template>
    </el-upload>
    <div v-for="(file, index) in fileList" :key="index" class="file-item">
      <img :src="file.url" alt="uploaded image" class="preview-image" />
      <el-progress :percentage="file.percentage" />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const fileList = ref([])

const handlePreview = (file) => {
  console.log('Preview file:', file)
}

const handleRemove = (file, fileList) => {
  console.log('Remove file:', file, fileList)
}

const handleChange = (file, fileList) => {
  console.log('File change:', file, fileList)
}

const handleProgress = (event, file, fileList) => {
  file.percentage = Math.round((event.loaded / event.total) * 100)
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt500K = file.size / 1024 < 500

  if (!isJPG && !isPNG) {
    this.$message.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt500K) {
    this.$message.error('上传图片大小不能超过 500KB!')
    return false
  }
  return true
}

const handleExceed = (files, fileList) => {
  this.$message.warning('最多只能上传 3 张图片')
}
</script>

<style scoped>
.upload-photos {
  padding: 20px;
}

.upload-demo {
  margin-bottom: 20px;
}

.file-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.preview-image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  object-fit: cover;
}
</style>